<template>
	<view class="my_wrapper">
		<view class="user_wrap">
			<view class="header">
				<view class="avatar">			
					<img :src="userInfo.avatar" alt="user avatar" v-if="Object.keys(userInfo).length > 0" />	
					<img :src="errorImage" v-else />
					<text class="nickname">{{userInfo.nickname}}</text>
				</view>
				<view class="message">
					<img @click="GotoChat" src="~@/static/img/msg_icon.svg" alt="message icon" />
				</view>
			</view>
			<view class="buy_list">
				<view class="buy_item" @click="GotoBuyDetail(0)">
					<view class="quantity">{{userInfo.purchased || 0}}</view>
					<text>我已购买</text>
				</view>
				<view class="buy_item" @click="GotoBuyDetail(1)">
					<view class="quantity">{{userInfo.coupon || 0}}</view>
					<text>优惠券</text>
				</view>
				<view class="buy_item" @click="GotoBuyDetail(2)">
					<view class="quantity">{{userInfo.collect || 0}}</view>
					<text>我的收藏</text>
				</view>
				<view class="buy_item" @click="GotoBuyDetail(3)">
					<view class="quantity"><text class="icon">￥</text>{{userInfo.myprice || 0 }}</view>
					<text>我的账户</text>
				</view>
			</view>
			<view class="order_wrap">
				<view class="order_header">
					<view class="title">订单</view>
					<view class="more" @click="GotoAllOrder(0)">查看全部订单&nbsp;<i class="iconfont icon-arrow-right"></i></view>
				</view>
				<view class="order_list">
					<view class="order_item" @click="GotoOrderList(1)">
						<i class="iconfont icon-daifukuan"></i>
						<text class="name">待付款</text>
					</view>
					<view class="order_item" @click="GotoOrderList(2)">
						<i class="iconfont icon-31daishouhuo"></i>
						<text class="name">待收获</text>
					</view>
					<view class="order_item" @click="GotoOrderList(3)">
						<i class="iconfont icon-daipingjia"></i>
						<text class="name">待评价</text>
					</view>
					<view class="order_item" @click="GotoOrderList(4)">
						<i class="iconfont icon-tuikuan"></i>
						<text class="name">退款</text>
					</view>
				</view>				
			</view>
			<view class="learn_center" @click="GotoLearnCenter">
				<view class="label">学习中心</view>
				<view class="report">
					<text class="round">新学习报告</text>
					<i class="iconfont icon-arrow-right"></i>
				</view>
			</view>
			<view class="learn_tools">
				<view class="label">学习工具</view>
				<view class="learn_list">
					<view class="learn_item" @click="GotoExchangeCurriculum">
						<i class="iconfont icon-duihuan"></i>
						<text class="name">兑换课程</text>
					</view>					
				</view>
			</view>
			<view class="exchange_center">
				<view class="item_cell" @click="GotoExchangeCenter">
					<view class="label">兑换中心</view>
					<view class="direction">
						<i class="iconfont icon-arrow-right"></i>
					</view>
				</view>				
			</view>
			<view class="exchange_center">
				<view class="item_cell" @click="GotoAccountSetting">
					<view class="label">账号设置</view>
					<view class="direction">
						<i class="iconfont icon-arrow-right"></i>
					</view>
				</view>
			</view>
		</view>
		<PageNavBar :tabIndex="3" />
		<!-- h5登录 -->
		<view class="h5_wrap" v-if="device == 'H5' && pcLoginVisible">
			<view class="mask"></view>
			<view class="login_wrap">
				<view class="uni-form-item">
					<view class="title">手机号</view>
					<input class="uni-input" type="number" v-model="loginParams.tel" placeholder="请输入手机号" />
				</view>
				<view class="uni-form-item">
					<view class="title">密码</view>
					<input class="uni-input" type="password" v-model="loginParams.password" placeholder="请输入密码" />
				</view>
				<view class="uni-btn-v">
					<button class="submit_btn" @click="userLogin">登录</button>
					<button class="reg_btn" @click="userRegister">注册</button>
				</view>
			</view>			
		</view>
		<!-- 微信公众号登录 -->
		<u-popup :show="wxLoginVisible" :round="10" mode="bottom" :closeOnClickOverlay="true" @close="userCancel">
			<view class="wxLogin_wrap">
				<view class="title">为给您提供更好的服务</view>
				<text class="intro">我们将通过《服务协议》、《隐私政策》和《商家隐私声明》帮助您了解我们收集、使用、存储和共享个人信息的情况</text>
				<view class="uni-btn-v">
					<button type="primary" class="submit_btn" @click="agreeContinue">同意并继续</button>
					<button class="cancel_btn" @click="userCancel">取消</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	// https://www.nashicike.top/pages/my/index?shop_name=db&code=051shoml2obkpd4yoyml2Yyz9e1shomK&state=STATE
	import { api_getShopname,api_getWxAgreeAdress,api_publicNumberLogin,api_getUserInfo,api_setUserPhone,api_H5BrowserLogin,api_tokenOverdue } from '@/api/api'
	import * as type from '../../utils/device'
	import { URLParams } from '@/utils/util'
	import PageNavBar from '@/components/nav_footer/index.vue'
	export default {
		components: { PageNavBar },
		data() {
			return {
				loginParams: {
					tel: '',
					password: ''
				},
				rules: {
					tel: { reg: /^1[3-9]\d{9}$/,name: 'tel',label: '手机号',msg: '手机号不合法' },
					password: { reg: /^\w+$/,name: 'password',label: '密码',msg: '密码不合法' },
				},
				pcLoginVisible: false,
				wxLoginVisible: false,
				token: uni.getStorageSync('token'),
				publicNumberCode: '0213emGa1yyJpH0tLhIa1FumQo23emGs',
				userInfo: {},
				errorImage: require('@/static/img/avatar.png'),
			}
		},
		onLoad() {
			this.getUrl()
			this.pageValidor();	
			this.setToken();
			this.getUserInfo();
		},
		computed: {
			device(){
				return type.default;
			},
		},
		created(){
					
		},
		methods: {
			pageValidor(){	// 判断是否存在token		
				let wxLogin = uni.getStorageSync('wxLoginTag');
				let pcLogin = uni.getStorageSync('h5LoginTag');
				if (!this.token) {
					this.wxLoginVisible = this.device == 'H5-WEIXIN' && !wxLogin ? true : false;
					this.pcLoginVisible = this.device == 'H5' && !pcLogin ? true: false;
				}
			},
			setToken(){	// 设置code值并请求接口获取token
				const checkUrl = new URLSearchParams(window.location.search);
				if(checkUrl.get('token')){
					uni.setStorageSync('token',checkUrl.get('token'))
				}		
			},
			GetShopName(){	// 获取店铺名称				
				api_getShopname().then(res => {
					if (res.code == 1) {
						uni.setStorageSync('company_name',res.data.shopname);
					} else {
						uni.showToast({ title: res.msg,icon: 'error' });
					}
				}).catch(err => console.log(err));
			},
			getUserInfo(){	// 公众号 -- 获取用户信息
				let token = uni.getStorageSync('token')
				if (token) {										
					api_getUserInfo().then(res => {					
						let { code,data,msg } = res;						
						if (code == 1) {
							this.userInfo = data;							
							uni.setStorageSync('userInfo',data);
						} else {
							uni.showToast({ title: msg,icon: 'error' });
						}
					}).catch(err => {						
						console.log(err);
					})
				}				
			},
			agreeContinue(){	// 微信公众号 -- 同意并继续
				api_getWxAgreeAdress().then(res => {
					console.log(res)
					let { code,data,msg } = res;
					if (code == 1) {
						this.wxLoginVisible = false;
						uni.setStorageSync('wxLoginTag',1);
						this.GetShopName();
						window.location.href = data.url;
					
					} else {
						uni.showToast({ title: msg,icon: 'error' });
					}
				}).catch(err => console.log(err));
			},
			publicNumberLogin(){	// 微信公众号 -- 登录获取token
				let token = uni.getStorageSync('token')
				// uni.setStorageSync('token','eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJhdWQiOiIiLCJpYXQiOjE3MTYxNzI5MTAsIm5iZiI6MTcxNjE3MjkyMCwiZXhwIjoxNzE2Nzc3NzEwLCJkYXRhIjp7InVpZCI6MTk5fX0.1vw80zpTUYPTb-oyUgL7NdO8BWO8SgMu_yTmrsToyP4');
				if (!token && window.location.href.indexOf('https://') > -1) {
					api_publicNumberLogin({code: this.publicNumberCode}).then(res => {
						let { code,data,msg } = res;
						if (code == 1) {
							uni.setStorageSync('token',data.token);
							uni.showToast({ title: '登录成功',icon: 'success' });
							this.getUserInfo();						
						} else {
							uni.showToast({ title: msg,icon: 'error' });
						}
					}).catch(err => console.log(err));
				}				
			},
			GotoChat(){	// 进入聊天列表
				if (!this.token) {
					this.wxLoginVisible = true;
					return;
				}
				uni.navigateTo({ url: '/pages/chat/index' });
			},
			userLogin(){	// h5 -- 登录
				let bool = this.validField(this.loginParams,this.rules);
				let query = { phone: this.loginParams.tel, password: this.loginParams.password };
				if (bool) {
					api_H5BrowserLogin(query).then(res => {
						uni.showToast({	title: res.msg,icon: res.code == 1 ? 'success' : 'error' });
						if (res.code == 1) {
							this.pcLoginVisible = false;
							uni.setStorageSync('token', res.data.token);
							uni.setStorageSync('frontrefreshtoken', res.data.refreshtoken);							               
							uni.setStorageSync('h5LoginTag', 1);
							this.getUserInfo();
						} else {
							console.log('error code')
						}
						
					}).catch(err => console.log(err));
				}
			},			
			validField(obj,reg){	// 验证表单相关字段值
				let keys = Object.keys(obj);
				let initNum = 0;
				function recur(arr, i) {
				    let n = arr[i];						
				    if (obj[n].length > 0) {
				        if (!reg[n]['reg'].test(obj[n])) {
				            uni.showToast({ title: reg[n]['msg'],icon: 'error' });
				            return false;
				        }				        
				        i++;
				        if (i < arr.length) {
				            return recur(arr, i);
				        } else {
				            return true;
				        }
				    } else {
				        uni.showToast({ title: `${reg[n].label}不能为空`,icon: 'error' });
				        return false;
				    }
				}
				return recur(keys,initNum);
			},
			userRegister(){	// h5 -- 注册	
				uni.navigateTo({ url: '/pages/register/index' });	
			},						
			userCancel(){	// 微信公众号 -- 取消				
				this.wxLoginVisible = false;
			},
			GotoBuyDetail(n){	// 已购、优惠券、收藏、账户				
				if (!this.token) {
					this.wxLoginVisible = true;
					return;
				}
				n == 0 && uni.navigateTo({ url: `/pages/purchased/index` });
				n == 1 && uni.navigateTo({ url: `/pages/coupon/index?subIndex=0` });
				n == 2 && uni.navigateTo({ url: `/pages/collection/index` });
				n == 3 && uni.navigateTo({ url: `/pages/account/index?money=${this.userInfo.myprice}` });							
			},
			GotoAllOrder(n){	// 查看全部订单		
				if (!this.token) {
					this.wxLoginVisible = true;
					return;
				}
				uni.navigateTo({ url: `/pages/order/index?subIndex=${n}` });
			},
			GotoOrderList(n){	// 订单 -- 选项选择
				let token = uni.getStorageSync('token');
				if (!token) {
					this.wxLoginVisible = true;
					return;
				}
				uni.navigateTo({ url: `/pages/order/index?subIndex=${n}` });
			},
			GotoLearnCenter(){	// 学习中心
				if (!this.token) {
					this.wxLoginVisible = true;
					return;
				}
				uni.navigateTo({ url: `/pages/learn_center/index?subIndex=0` });	
			},
			GotoExchangeCurriculum(){	// 兑换课程		
				if (!this.token) {
					this.wxLoginVisible = true;
					return;
				}
				uni.navigateTo({ url: `/pages/exchange_curriculum/index` });	
			},
			GotoExchangeCenter(){	//	兑换中心
				if (!this.token) {
					this.wxLoginVisible = true;
					return;
				}
				uni.navigateTo({ url: `/pages/exchange_center/index?subIndex=0` });
			},
			GotoAccountSetting(){	// 账号设置
				if (!this.token) {
					this.wxLoginVisible = true;
					return;
				}
				uni.navigateTo({ url: `/pages/setting/index` });
			},
		}
	}
</script>

<style lang="scss" scoped>
	.my_wrapper{
		height: calc(100vh - 100px);
		background-color: #eee;
		padding: 0 0 50px 0;
		overflow-y: auto;
		.user_wrap{
			.header{
				display: flex;
				justify-content: space-between;
				padding: 20px;
				background-color: #333;
				.avatar{
					display: flex;
					font-size: 15px;
					color: #fff;
					img{
						display: block;
						width: 60px;
						height: 60px;
						border-radius: 50%;
						margin: 0;
					}
					.nickname{
						vertical-align: top;
						margin: 10px 0 0 10px;
					}
				}
				.message{
					width: 20px;
					img{
						width: 20px;
						height: 20px;
					}
				}
			}
			.buy_list{
				display: flex;
				align-items: center;
				justify-content: space-between;
				background-color: #fff;
				padding: 10px 0;
				margin: 0 0 10px;
				.buy_item{
					flex: 1;
					font-size: 10px;
					text-align: center;
					color: #666;
					.quantity{
						display: block;
						font-size: 16px;
						font-weight: bold;
						color: #333;
						margin: 0 auto;
						.icon{
							font-size: 10px;
							font-weight: normal;
						}
					}
				}
			}
			.order_wrap{
				background-color: #fff;
				margin: 0 0 10px;
				.order_header{
					display: flex;
					justify-content: space-between;
					padding: 10px;
					.title{
						font-size: 12px;
						color: #333;
					}
					.more{
						font-size: 12px;
						color: #999;
						.iconfont{
							float: right;
							font-size: 12px;
							margin: 0 0 0 3px;
						}
					}
				}
				.order_list{
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 10px 0;
					.order_item{
						flex: 1;
						text-align: center;
						.iconfont{
							display: block;
							font-size: 20px;
							margin: 0 auto;
						}
						.name{
							font-size: 10px;
						}
					}
				}
			}
			.learn_center{
				display: flex;
				align-items: center;
				justify-content: space-between;
				background-color: #fff;
				padding: 10px;
				margin: 0 0 10px;
				.label{
					display: flex;
					font-size: 12px;
				}
				.report{
					display: flex;
					align-items: center;
					.round{
						float: left;
						border-radius: 10px;
						background-color: rgba(12,187,8,.16);
						padding: 0 5px;
						font-size: 10px;
						line-height: 16px;
						color: #0cbb08;
					}
					.iconfont{
						font-size: 12px;
						margin: 0 0 0 3px;
					}
				}
			}		
			.learn_tools{
				background-color: #fff;		
						margin: 0 0 10px 0;
				.label{
					font-size: 12px;
					padding: 10px;
				}
				.learn_list{
					overflow: hidden;			
					.learn_item{
						float: left;
						width: 25%;
						text-align: center;
						padding: 10px;
						box-sizing: border-box;
						.iconfont{
							display: block;
							font-size: 20px;
							margin: 0 auto;
						}
						.name{
							font-size: 10px;
						}
					}
				}
			}
			.exchange_center{
				background-color: #fff;
				padding: 0 10px;
				.item_cell{
					display: flex;
					align-items: center;
					justify-content: space-between;
					border-bottom: 1px solid #ebedf0;
					padding: 10px 0;
					.label{
						font-size: 12px;
					}
					.direction{
						.iconfont{
							font-size: 12px;
							margin: 0 0 0 3px;
						}
					}
				}				
			}
		}
		.h5_wrap{
			width: 100%;
			height: 100%;
			.mask{
				width: 100%;
				height: 100%;
				background-color: rgba(0,0,0,.3);
				position: fixed;
				left: 0;
				top: 0;
			}
			.login_wrap{
				width: 80%;
				border-radius: 16px;
				background-color: #fff;
				padding: 20px;
				position: absolute;
				left: 50%;
				top: 50%;
				-webkit-transform: translate(-50%,-50%);
				transform: translate(-50%,-50%);
				.uni-form-item{
					display: flex;
					align-items: center;
					border-bottom: 1px solid #ebedf0;				
					padding: 15px 0;
					margin: 0 0 10px;
					.title{
						width: 50px;
						font-size: 14px;
						text-align: right;
						margin: 0 10px 0 0;
					}	
					.uni-input{
						.uni-input-placeholder{
							font-size: 14px;
						}
					}
				}
				.uni-btn-v{
					display: flex;
					justify-content: space-between;
					margin: 30px auto 0;
					padding: 0 20px;
					button{		
						margin: 0;
						border-radius: 30px;
						padding: 0 40px;
					}
					.submit_btn{
						background-color: #07c160;
						color: #fff;
						border: none;
					}
					.reg_btn{
						background-color: #fff;
						border: 1px solid #333;
					}
				}
			}
		}
		.wxLogin_wrap{
			width: 100%;
			border-radius: 16px 16px 0 0;
			background-color: #fff;
			padding: 0 10px 10px;
			box-sizing: border-box;			
			.title{
				font-size: 14px;
				line-height: 32px;
				font-weight: bold;
			}
			.intro{
				font-size: 13px;
				line-height: 18px;
			}
			.uni-btn-v{
				margin: 20px 0 0;
				button{
					font-size: 14px;
					border-radius: 30px;
					margin: 0 0 10px;
					background-color: #07c160;
				}
				.cancel_btn{
					background-color: #fff;
					border: 1px solid #ebedf0;
				}
			}
		}
	}
</style>
